<template>
  <div class="order-management">
    <h2>加盟商家订单管理</h2>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单ID">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单ID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="准备取件" value="ready_for_pickup" />
            <el-option label="已取件" value="picked_up" />
            <el-option label="洗涤中" value="washing" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="租赁中" value="rentalling" />
            <el-option label="待归还" value="to_be_returned" />
            <el-option label="已归还" value="returned" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.serviceType" placeholder="请选择订单类型" clearable>
            <el-option label="仅取件洗衣" value="washing_pickup_only" />
            <el-option label="全程洗衣" value="washing_full_service" />
            <el-option label="仅取件租赁" value="rental_pickup_only" />
            <el-option label="全程租赁" value="rental_full_service" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table
        :data="merchantOrders"
        style="width: 100%"
        border
        v-loading="loading"
        :default-sort="{ prop: 'orderId', order: 'descending' }"
    >
      <el-table-column prop="orderId" label="订单ID" width="100" sortable />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="merchantId" label="商家ID" width="100" />
      <el-table-column prop="serviceType" label="服务类型" width="150">
        <template #default="scope">
          {{ serviceTypeText(scope.row.serviceType) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderAmount" label="订单金额" width="120" />
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ statusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openOrderDetails(scope.row)">查看</el-button>
          <el-button type="danger" size="small" @click="deleteOrder(scope.row.orderId)">删除</el-button>
          <el-button type="info" size="small" @click="viewOrderReview(scope.row.orderId)">查看评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalOrders"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单ID">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
        <el-descriptions-item label="商家ID">{{ currentOrder.merchantId }}</el-descriptions-item>
        <el-descriptions-item label="服务类型">{{ serviceTypeText(currentOrder.serviceType) }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">{{ currentOrder.orderAmount }}</el-descriptions-item>
        <el-descriptions-item label="定金金额">{{ currentOrder.depositAmount }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ statusText(currentOrder.status) }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ currentOrder.address || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.contactNumber || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentOrder.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(currentOrder.updatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="租赁时长">{{ currentOrder.rentalDuration || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{ currentOrder.addressLatitude || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="经度">{{ currentOrder.addressLongitude || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="租赁ID">{{ currentOrder.rentalId || 'N/A' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 评价详情弹窗 -->
    <el-dialog v-model="reviewDialogVisible" title="评价详情" width="50%">
      <el-descriptions v-if="currentReview" :column="1" border>
        <el-descriptions-item label="评价ID">{{ currentReview.reviewId }}</el-descriptions-item>
        <el-descriptions-item label="订单ID">{{ currentReview.orderId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentReview.userId }}</el-descriptions-item>
        <el-descriptions-item label="商家ID">{{ currentReview.merchantId }}</el-descriptions-item>
        <el-descriptions-item label="评分">
          <el-rate v-model="currentReview.rating" disabled show-score text-color="#ff9900" />
        </el-descriptions-item>
        <el-descriptions-item label="是否满意">
          <el-tag :type="currentReview.isSatisfied === 'yes' ? 'success' : 'danger'">
            {{ currentReview.isSatisfied === 'yes' ? '满意' : '不满意' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="评价时间">{{ formatDateTime(currentReview.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(currentReview.updatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="是否确认">
          <el-tag :type="currentReview.confirmed ? 'success' : 'warning'">
            {{ currentReview.confirmed ? '已确认' : '未确认' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="情感分析">
          <el-tag :type="getSentimentType(currentReview.sentiment)">
            {{ sentimentText(currentReview.sentiment) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="版本">{{ currentReview.version }}</el-descriptions-item>
        <el-descriptions-item label="评价内容">
          <div class="comment-content">{{ currentReview.comment || '暂无评价内容' }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <el-empty v-else description="该订单暂无评价" />
      <template #footer>
        <el-button @click="reviewDialogVisible = false">关闭</el-button>
        <el-button v-if="currentReview && !currentReview.confirmed" type="success" @click="confirmReview(currentReview.reviewId)">确认评价</el-button>
        <el-button v-if="currentReview" type="danger" @click="deleteReview(currentReview.reviewId)">删除评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';

export default {
  name: 'MerchantOrderManagement',
  data() {
    return {
      merchantOrders: [],
      totalOrders: 0,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      reviewDialogVisible: false,
      currentOrder: {},
      currentReview: null,
      loading: false,
      searchForm: {
        orderId: '',
        status: '',
        serviceType: '',
      },
    };
  },
  computed: {
    adminInfo() {
      return this.$store.state.adminInfo || { username: '超级星', role: 'super' };
    },
  },
  mounted() {
    this.fetchMerchantOrders();
  },
  methods: {
    fetchMerchantOrders: _.debounce(async function() {
      try {
        this.loading = true;
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error('未登录，请先登录');
          return;
        }
        const response = await axios.get('/api/merchant-orders', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            orderId: this.searchForm.orderId || null,
            status: this.searchForm.status || null,
            serviceType: this.searchForm.serviceType || null,
          },
          headers: {
            Authorization: `Bearer ${token}`,
            'Role': encodeURIComponent(this.adminInfo.role || ''),
            'Username': encodeURIComponent(this.adminInfo.username || ''),
          },
        });
        this.merchantOrders = response.data.data || [];
        this.totalOrders = response.data.total || 0;
      } catch (error) {
        this.$message.error('获取加盟商家订单失败: ' + (error.response?.data?.message || error.message));
        console.error('获取加盟商家订单失败:', error.response?.data || error);
      } finally {
        this.loading = false;
      }
    }, 300),

    handleSearch() {
      this.currentPage = 1;
      this.fetchMerchantOrders();
    },

    resetSearch() {
      this.searchForm = { orderId: '', status: '', serviceType: '' };
      this.currentPage = 1;
      this.fetchMerchantOrders();
    },

    openOrderDetails(order) {
      this.currentOrder = { ...order };
      this.dialogVisible = true;
    },

    deleteOrder(orderId) {
      this.$confirm('确定删除此订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(async () => {
            try {
              const token = sessionStorage.getItem('token');
              await axios.delete(`/api/merchant-orders/${orderId}`, {
                headers: {
                  Authorization: `Bearer ${token}`,
                  'Role': encodeURIComponent(this.adminInfo.role || ''),
                  'Username': encodeURIComponent(this.adminInfo.username || ''),
                },
              });
              this.$message.success('订单删除成功');
              this.fetchMerchantOrders();
            } catch (error) {
              this.$message.error('删除订单失败: ' + (error.response?.data?.message || error.message));
              console.error('删除订单失败:', error.response?.data || error);
            }
          })
          .catch(() => {
            this.$message.info('已取消删除');
          });
    },

    viewOrderReview: _.debounce(async function(orderId) {
      try {
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error('未登录，请先登录');
          return;
        }
        const response = await axios.get(`/api/reviews/byOrderId/${orderId}`, {
          headers: {
            Authorization: `Bearer ${token}`,
            'Role': encodeURIComponent(this.adminInfo.role || ''),
            'Username': encodeURIComponent(this.adminInfo.username || ''),
          },
        });
        this.currentReview = response.data;
        this.reviewDialogVisible = true;
      } catch (error) {
        if (error.response?.status === 404) {
          this.currentReview = null;
          this.reviewDialogVisible = true;
        } else {
          this.$message.error('获取评价失败: ' + (error.response?.data?.message || error.message));
          console.error('获取评价失败:', error.response?.data || error);
        }
      }
    }, 300),

    deleteReview(reviewId) {
      this.$confirm('确定删除此评价吗？此操作不可撤销', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(async () => {
            try {
              const token = sessionStorage.getItem('token');
              await axios.delete(`/api/reviews/${reviewId}`, {
                headers: {
                  Authorization: `Bearer ${token}`,
                  'Role': encodeURIComponent(this.adminInfo.role || ''),
                  'Username': encodeURIComponent(this.adminInfo.username || ''),
                },
              });
              this.$message.success('评价删除成功');
              this.reviewDialogVisible = false;
            } catch (error) {
              this.$message.error('删除评价失败: ' + (error.response?.data?.message || error.message));
              console.error('删除评价失败:', error.response?.data || error);
            }
          })
          .catch(() => {
            this.$message.info('已取消删除');
          });
    },

    confirmReview: _.debounce(async function(reviewId) {
      this.$confirm('确定确认此评价吗？确认后不可更改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(async () => {
            try {
              const token = sessionStorage.getItem('token');
              await axios.put(`/api/reviews/confirm/${reviewId}`, null, {
                headers: {
                  Authorization: `Bearer ${token}`,
                  'Role': encodeURIComponent(this.adminInfo.role || ''),
                  'Username': encodeURIComponent(this.adminInfo.username || ''),
                },
              });
              this.$message.success('评价确认成功');
              // 更新当前评价的 confirmed 状态
              this.currentReview.confirmed = true;
            } catch (error) {
              this.$message.error('确认评价失败: ' + (error.response?.data?.message || error.message));
              console.error('确认评价失败:', error.response?.data || error);
            }
          })
          .catch(() => {
            this.$message.info('已取消确认');
          });
    }, 300),

    handlePageChange(page) {
      this.currentPage = page;
      this.fetchMerchantOrders();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchMerchantOrders();
    },

    serviceTypeText(serviceType) {
      const map = {
        washing_pickup_only: '仅取件洗衣',
        washing_full_service: '全程洗衣',
        rental_pickup_only: '仅取件租赁',
        rental_full_service: '全程租赁',
      };
      return map[serviceType] || serviceType;
    },

    statusText(status) {
      const map = {
        pending: '待处理',
        ready_for_pickup: '准备取件',
        picked_up: '已取件',
        washing: '洗涤中',
        delivering: '配送中',
        completed: '已完成',
        in_progress: '进行中',
        rentalling: '租赁中',
        to_be_returned: '待归还',
        returned: '已归还',
      };
      return map[status] || status;
    },

    getStatusTagType(status) {
      const map = {
        pending: 'info',
        ready_for_pickup: 'warning',
        picked_up: 'success',
        washing: 'primary',
        delivering: 'primary',
        completed: 'success',
        in_progress: 'primary',
        rentalling: 'primary',
        to_be_returned: 'warning',
        returned: 'success',
      };
      return map[status] || '';
    },

    formatDateTime(dateTime) {
      if (!dateTime) return 'N/A';
      const date = new Date(dateTime);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      }).replace(/\//g, '-');
    },

    getSentimentType(sentiment) {
      const map = {
        positive: 'success',
        negative: 'danger',
        neutral: 'info',
      };
      return map[sentiment] || 'info';
    },

    sentimentText(sentiment) {
      const map = {
        positive: '正面',
        negative: '负面',
        neutral: '中性',
      };
      return map[sentiment] || '中性';
    },
  },
};
</script>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.search-filter {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.el-table {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.comment-content {
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
  min-height: 50px;
  word-break: break-all;
}
</style>